﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MySqlSync.Core.Interfaces;
using MySqlSync.Core.Models;
using MySqlSync.DataAccess;
using MySqlSync.Kafka;
using MySqlSync.SyncService;

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("MySQL 同步消费者服务正在启动...");

        // 使用using确保CancellationTokenSource正确释放
        using var cts = new CancellationTokenSource();
        Console.CancelKeyPress += (sender, e) =>
        {
            e.Cancel = true;
            cts.Cancel();
            Console.WriteLine("正在停止服务，请等待...");
        };

        try
        {
            // 使用using确保主机资源正确释放
            using var host = CreateHostBuilder(args).Build();

            // 运行主机，自动管理托管服务的生命周期
            await host.RunAsync(cts.Token);
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("服务已被用户终止");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"服务启动失败: {ex.Message}");
            Console.WriteLine(ex.StackTrace);
        }

        Console.WriteLine("服务已退出");
    }

    static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
                config.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true);
                config.AddCommandLine(args);
            })
            .ConfigureServices((hostContext, services) =>
            {
                // 配置绑定
                var syncConfig = hostContext.Configuration.Get<SyncConfig>() ??
                    throw new InvalidOperationException("无法加载同步配置");
                services.AddSingleton(syncConfig);
                services.AddSingleton(syncConfig.Kafka);
                services.AddSingleton(syncConfig.Redis);
                //services.AddSingleton<KafkaConfig>();
                // 服务注册：使用托管服务模式管理SyncConsumerService
                services.AddSingleton<IDbService, DbService>();
                services.AddSingleton<IKafkaConsumerService, KafkaConsumerService>();
                // 注册为托管服务，同时支持通过接口获取
                services.AddHostedService<SyncConsumerService>();
                services.AddSingleton<ISyncConsumerService>(provider =>
                    provider.GetRequiredService<IHostedService>() as SyncConsumerService ??
                    throw new InvalidOperationException("无法解析SyncConsumerService"));
            });
}
